package com.fowo.api.common.validator;

import com.fowo.api.common.util.SheetUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;

/**
 * 提供文本类型的小数的校验处理
 */
public class IntegerStringValidator implements ConstraintValidator<IntegerString, String> {
    private IntegerString annotation;

    @Override
    public void initialize(IntegerString constraintAnnotation) {
        this.annotation = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        try {
            Integer d = SheetUtils.toInteger(value);
            if (d != null) {
                if(Integer.valueOf(annotation.min()).compareTo(d) > 0) {
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate(
                            String.format("%s不能小于%d", annotation.label(), annotation.min())
                    ).addConstraintViolation();
                    return false;
                }
                if(Integer.valueOf(annotation.max()).compareTo(d) < 0) {
                    context.disableDefaultConstraintViolation();
                    context.buildConstraintViolationWithTemplate(
                            String.format("%s不能大于%d", annotation.label(), annotation.min())
                    ).addConstraintViolation();
                    return false;
                }
            }
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }
}
